
package com.zkmonitor.interceptor;

import com.zkmonitor.common.Auth;
import com.zkmonitor.exception.ShepherException;
import com.zkmonitor.util.AuthStrategy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private AuthStrategy authStrategy;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Auth annotation = getAnnotation(handlerMethod);

            if (annotation != null && !authStrategy.validate(request, annotation.value())) {
                throw ShepherException.createNoAuthorizationException();
            }
        }

        return true;
    }

    private Auth getAnnotation(HandlerMethod handlerMethod) {
        Auth annotation = handlerMethod.getMethodAnnotation(Auth.class);

        Class<?> beanType = handlerMethod.getBeanType();
        if (beanType.isAnnotationPresent(Auth.class)) {
            annotation = beanType.getAnnotation(Auth.class);
        }
        return annotation;
    }

}
